<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-05-21
 * Time: 14:37
 */

namespace plugins\wechat\controller;


use cmf\controller\PluginBaseController;
use plugins\wechat\common\WechatController;
use think\Db;

class WeixinController extends PluginBaseController {
    public function init() {
        $wechat_config = Db::name('plugin_wechat_config')->find();

        $options = array (
            'token' => $wechat_config ["token"], // 填写你设定的key
            'encodingaeskey' => $wechat_config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $wechat_config ["appid"], // 填写高级调用功能的app id
            'appsecret' => $wechat_config ["appsecret"], // 填写高级调用功能的密钥
            //'partnerid' => $config ["partnerid"], // 财付通商户身份标识
            //'partnerkey' => $config ["partnerkey"], // 财付通商户权限密钥Key
            //'paysignkey' => $config ["paysignkey"],  // 商户签名密钥Key
            'debug' => TRUE
        );
        //$weObj = new Wechat($options);
        $weObj = new WechatController($options);
        return $weObj;
    }

    /**
     * 对接微信地址
     * 即是跟微信互动的地址（自定义回复，关注）
     */
    public function index(){
        $weObj = $this->init();
        $weObj -> valid();
        $type = $weObj -> getRev() -> getRevType();
        switch ($type){
        	 case WechatController::MSGTYPE_TEXT :           //接收文本信息，发起回复
                $key = $weObj->getRev()->getRevContent();
                $reply = Db::name('plugin_wechat_reply')->where(['key'=>['like','%'.$key.'%'],'status'=>1])->select();
                
                if (count($reply)){
                    for ($i=0;$i<count($reply);$i++){
                        if ($reply[$i]['type'] == 1){
                            $newsArr[$i] = [
                                'Title' => $reply[$i]['title'],
                                'Description' => $reply[$i]['description'],
                                'PicUrl' => cmf_get_image_url($reply[$i]['picture']),
                                'Url' => $reply[$i]['url'].'?uid='.$weObj->getRevFrom(),
                            ];
                        }else{
                            $weObj->text($reply[$i]['title'])->reply();
                            exit;
                        }
                    }
                    
                    $weObj->getRev()->news($newsArr)->reply();
                }
                exit;
                break;
            case WechatController::MSGTYPE_EVENT :
                $event_type = $weObj->getRev()->getRevEvent();
      
            	if($event_type['event'] == 'subscribe'){
            		$res=$weObj->text();	
            		// $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb6c09ceb8e8f8117&redirect_uri=http%3A%2F%2Fyouyi.52wgj.com%2Fplugin%2Fwechat%2Fweixin%2Fauthorize&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                    $this->redirect($url);     
                }elseif ($event_type['event'] == 'unsubscribe'){
                	$weObj->text($subscribe_reply[$i]['title'])->reply();
             }
                
                break;
                default:
                	$weObj->text ( "help info" )->reply ();
                break;
            }
    }

    /**
     * 生成公众号菜单
     */
    public function createMenu(){
        //顶级菜单
        $top_menu = Db::name('plugin_wechat_menu')->where(['pid'=>'0','status'=>'1'])->order(['order'=>'desc','id'])->select();
        foreach($top_menu as $k=>$v){
            $data[$k]['name'] = $v['name'];
            $child_menu = Db::name('plugin_wechat_menu')->where(['pid'=>$v['id'],'status'=>1])->order(['order'=>'desc','id'])->select();
            if (count($child_menu)){
                foreach ($child_menu as $ck=>$cv){
                    if ($cv['type'] == 'view'){
                        $_key = 'url';
                        $_val = $cv['url'];
                        $data[$k]['sub_button'][] = ['type'=>$cv['type'],'name'=>$cv['name'],$_key=>$_val];
                    }elseif ($cv['type'] == 'click'){
                        $_key = 'key';
                        $_val = $cv['event_key'];
                        $data[$k]['sub_button'][] = ['type'=>$cv['type'],'name'=>$cv['name'],$_key=>$_val];
                    }elseif($cv['type'] == 'miniprogram'){
                        $_key = 'url';
                        $_val = $cv['url'];
                        $data[$k]['sub_button'][] = ['type'=>$cv['type'],'name'=>$cv['name'],$_key=>$_val,'appid'=>$cv['mini_appid'],'pagepath'=>$cv['mini_pagepath']];
                    }
                }
            }else{
                
                $data[$k]['type'] = $v['type'];
                if($v['type'] == 'view'){
                    $data[$k]['url'] = $v['url'];
                }elseif($v['type'] == 'click'){
                    $data[$k]['key'] = $v['event_key'];
                }elseif($v['type'] == 'miniprogram'){
                    $data[$k]['url'] = $v['url'];
                    $data[$k]['appid'] = $v['mini_appid'];
                    $data[$k]['pagepath'] = $v['mini_pagepath'];
                }
            }
        }
        $wechat_menu['button'] = $data;
        $weObj = $this->init();
        
        $weObj->createMenu($wechat_menu) ? $this->success ( "微信公众号生成菜单成功!" ) : $this->error ( "微信公众号生成菜单失败!" ) ;
    }
     /*
   	*网页授权
   */
  public function authorize(){
        $code = $_GET['code'];
        //获取access_token
    	$appid="wxb6c09ceb8e8f8117";
    	$appsecret="471960b7a215c1af84e4ba2b9c083b8f";
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $response = json_decode(file_get_contents($url),true);
        $access_token = $response['access_token'];
   
        $openid= $response['openid'];
    	$userinfo = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        $response_user = json_decode(file_get_contents($userinfo),true);
    	return $this->fetch(
          	':authorize',
            [
              'nickname'  => $response_user['nickname'],
              'country'  => $response_user['country'],
              'province'  => $response_user['province'],
              'city'  => $response_user['city'],
              'headimgurl' => $response_user['headimgurl'],
            ]
        );
  }
}